package com.tmall.testgen.common.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class TransferHandler {
	private static final int SERIALIZED_INVOCATION_BYTE_ARRAY_INITIAL_SIZE = 1024;
	
	public static void writeObject(OutputStream outPutStream,Object obj) throws Exception{
		ByteArrayOutputStream baos = getByteArrayOutputStream(obj);
		baos.writeTo(outPutStream);
	}
	
	public static Object readObject(InputStream is) throws Exception{
		ObjectInputStream ois = new ObjectInputStream(is);
		return doReadRemoteInvocationResult(ois);
	}
	protected static Object doReadRemoteInvocationResult(ObjectInputStream ois)
			throws IOException, ClassNotFoundException {

		Object obj = ois.readObject();
		return  obj;
	}

	protected static ByteArrayOutputStream getByteArrayOutputStream(Object obj) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(SERIALIZED_INVOCATION_BYTE_ARRAY_INITIAL_SIZE);
		writeRemoteInvocation(obj, baos);
		return baos;
	}
	protected static void writeRemoteInvocation(Object obj, OutputStream os) throws IOException {
		ObjectOutputStream oos = new ObjectOutputStream(os);
		try {
			doWriteRemoteInvocation(obj, oos);
		}
		finally {
			oos.close();
		}
	}
	protected static void doWriteRemoteInvocation(Object obj, ObjectOutputStream oos) throws IOException {
		oos.writeObject(obj);
	}
}
